var pageScript =
{
	setPage: function(activeNav, doReplace, noState)
	{
		$(".navbar-item-selected").removeClass("navbar-item-selected");
		$(".page-selected").removeClass("page-selected");
		
		if (!activeNav || activeNav === "")
		{
			if (location.hash)
				activeNav = location.hash.substr(1);
			else
				activeNav = $(".navbar-item").attr("pagename");
		}
		
		var navName = "#" + activeNav; 		
		$(navName + "PageNav.navbar-item").addClass("navbar-item-selected");
		$(navName + "Page.page").addClass("page-selected");
		
		if (!noState)
		{
			if (doReplace)
				history.replaceState(activeNav, activeNav, "");
			else
				history.pushState(activeNav, activeNav, navName);
		}
	},
	addContainer: function(containerData)
	{
		var tabCount = $("#containerTabs .ui-tabs-panel").length - $("#containerTabs #tab-new-container").length;
		
		if (!containerData)
			containerData = new Container({"title": "Container " + (tabCount + 1).toString(), "size": 48, "id": new Date().getTime().toString()});
		
		var id = "tab-containers-" + containerData.id;
		var selector = "#" + id;
		$("#containerTabs").tabs("add", selector, containerData.title, tabCount);
		var newContainer = new Container(containerData);
		
		var newEditor = $.tmpl("containerEditor", containerData);
		$(selector).append(newEditor);
		
		if (containerData.items && containerData.items.length > 0)
			newContainer.add(containerData.items);
		
		newContainer.render($(selector));
		pageScript.fillEditor(newEditor, containerData);
		return newContainer;
	},
	addDummyTab: function()
	{
		var selector = "#tab-new-container";
		$("#containerTabs").tabs("add", selector, "+");
	},
	fillEditor: function(editor, containerData)
	{
		editor.find(".title").val(containerData.title);
		editor.find(".size").val(containerData.size);
		editor.find(".classes").val(containerData.classes.split(" "));
	}
};

$(window).bind("popstate", function(e)
{
	if (e.originalEvent.state)
		pageScript.setPage(e.originalEvent.state, false, true);
});

$(".navbar-item").live("click", function(e)
{
	pageScript.setPage($(this).attr("pagename"));
});

$("#settings-title").live("click", function(e)
{
	pageScript.setPage();
});

$("#containerTabs")
	.live("tabsselect", function(e, sender)
	{
		if (sender.panel.id === "tab-new-container")
		{
			e.preventDefault();
			var newCon = pageScript.addContainer();
			$("#containerTabs").tabs("select", newCon.id);
			options.setContainer(newCon);
		}
	})
	.live("sortstop", function(e, sender)
	{
		var tabs = $(this).find(".ui-tabs-nav li:not(:last) a");//:not(.ui-sortable-placeholder, .ui-sortable-helper)");
		var ids = [];
		tabs.each(function() {ids.push($(this).attr("href").replace("#tab-containers-", ""));});
		options.setContainerOrder(ids);
	})
	;


$(".ui-tabs .title.value").live("change", function(e)
{
	var field = $(this);
	var container = field.closest(".ui-tabs-panel").find(".container");
	
	var domId = field.closest(".ui-tabs-panel").attr("id");
	var id = container.data("id");
	var tab = field.closest(".ui-tabs").find(".ui-tabs-nav a[href='#" + domId + "']");
	
	var label = tab.find("span");
	var newValue = field.val();
	
	label.text(newValue);
	
	options.setContainer(id, function()
	{
		this.title = newValue;
	});
});
$(".ui-tabs .size.value").live("change", function(e)
{
	var field = $(this);
	var container = field.closest(".ui-tabs-panel").find(".container");
	
	var domId = field.closest(".ui-tabs-panel").attr("id");
	var id = container.data("id");
	
	var newValue = field.val();
	
	if (newValue < 48)
		container.removeClass("large").addClass("small");
	else if (newValue > 48)
		container.removeClass("small").addClass("large");
	else
		container.removeClass("large").removeClass("small");
	
	options.setContainer(id, function()
	{
		this.size = newValue;
	});
});
$(".ui-tabs .classes.value").live("change", function(e)
{
	var field = $(this);
	var container = field.closest(".ui-tabs-panel").find(".container");
	
	var domId = field.closest(".ui-tabs-panel").attr("id");
	var id = container.data("id");
	
	var newValue = "";
	
	var unclasses = field.closest(".editor").find(".classes").not(":checked");
	unclasses.each(function()
	{
		container.removeClass(this.value);
	});
	var classes = field.closest(".editor").find(".classes:checked");
	for (var i = 0; i < classes.length; i++)
	{
		if (newValue.length > 0)
			newValue += " ";
		newValue += classes[i].value;
		container.addClass(classes[i].value);
	}
	
	options.setContainer(id, function()
	{
		this.classes = newValue;
	});
});

$(".designer .ui-tabs .ui-tabs-nav li .tab-close").live("click", function(e)
{
	var field = $(this);
	var tab = field.closest("li");
	
	var tabIndex = tab.prevAll("li").length;
	
	e.preventDefault();

	if (!confirm("Fo sho?"))
		return;
	
	$("#containerTabs").tabs("remove", tabIndex);
	options.removeContainer(tabIndex);
});
	




$(document).ready(function()
{
	$(".ui-tabs").tabs({
		tabTemplate: "<li><a href='#{href}'>#{label}</a> <span class='tab-close'>&#x00d7;</span></li>"
	});
	
	options.displayVersion("#versionNumber");
	
	$("#containerTabs .ui-tabs-nav").sortable({ items: "li:not(:last)" });
	pageScript.setPage(null, true);
	
	if (location.search && location.search.length > 1)
	{
		var mode = location.search.substr(1).toLowerCase();
		switch (mode)
		{
			case "install":
			case "upgrade":
				$("#releasePage h1").after("<div class='notification'>" + textResources["label_detect_" + mode] + "</div>");
				break;
		}
	}
	
	var containers = options.get().containers;
	for (var i = 0; i < containers.length; i++)
	{
		pageScript.addContainer(containers[i]);
	}
	pageScript.addDummyTab();
	
	var sys = new Container("System", 48, "readOnly");
	sys.add([systemCommands.bookmarks, systemCommands.history, systemCommands.downloads, systemCommands.extensions]);
	sys.render($("#tab-items-system"));

	var opt = new Container("Options", 48, "readOnly");
	opt.add([systemCommands.appOptions, systemCommands.clearBrowserData, systemCommands.contentSettings, systemCommands.incognito, systemCommands.options]);
	opt.render($("#tab-items-options"));
	
	var dev = new Container("Development", 48, "readOnly");
	dev.add([systemCommands.plugins, systemCommands.stats, systemCommands.experimental]);
	dev.render($("#tab-items-development"));
	
	var apps = new Container("Apps", 48, "readOnly");
	apps.add([webStore, {"specialType": "appsExcept"}]);
	apps.render($("#tab-items-apps"));
	
	scripts.populateBookmarkTree(document.getElementById("bookmarkFolder"));
});

$("#bookmarkFolder").live("change", function(e)
{
	$("#tab-items-bookmarks .container").remove();
	var favs = new Container("Bookmarks", 16, "readOnly");
	favs.add([{"specialType": "bookmarkFolder", "specialTypeParam": this.value}]);
	favs.render($("#tab-items-bookmarks"));
});

$("#backToHome").live("click", function(e)
{
	location.assign("startpage.html");
});

$("#clearOptions").live("click", function(e)
{
	if (!confirm("Fo sho?"))
		return;
	options.clear();
	location.assign("startpage.html");
});

$("#processImport").live("click", function(e) {
  var imp = JSON.parse($('#importData').val());
  if (imp && imp.options) {
    localStorage.options = imp;
    alert("Okie dokie");
  } else {
    alert("Ooooh, so sorry!");
  }
});

$("#generateExport").live("click", function(e) {
  $('#exportData').val(JSON.stringify(localStorage));
  alert("Can't touch this");
});

